<template>
    <div class="edtiArticle">
        <div class="drawerTop">
            <el-form label-width="82px" size="default" :rules="editFormRules" :model="editForm" ref="editFormRef">
                <div class="title">编辑数字校园</div>
                <div class=seetingBox>
                    <el-form-item label="模块名称" prop="module_name">
                        <el-input clearable placeholder="请输入模块名称" v-model="editForm.module_name">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="全部分类">
                        <el-button type="primary" style="margin-bottom: 10px;margin-right: 10px;" class="white-bg-btn"
                            plain @click="Add">
                            <el-icon>
                                <CirclePlusFilled />
                            </el-icon>
                            添加分类
                        </el-button>
                        <el-tag v-show="item.name" v-for="(item, index) in typeList" :key="index" size="large"
                            effect="dark" type="primary" style="margin-right:10px;margin-bottom: 10px;">{{
                            item.name }}</el-tag>
                    </el-form-item>
                    <el-form-item label="所属分类" prop="type_id">
                        <el-select v-model="editForm.type_id" filterable clearable style="width:100%;"
                            placeholder="请选择所属分类" @change="changeType" :teleported="false">
                            <el-option v-for="(item, index) in typeList" :key="index" :label="item.name"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <div class="FriendLink" v-show="editForm.type_id"
                        v-for="(item, index) in typeList[currentIndex].childItem" :key="index">
                        <div class="leftBox">
                            <el-popover class="leftBoxPopover" :teleported="false" :visible="item.visible" ref="popover"
                                placement="left" width="360">
                                <template #reference>
                                    <div class="iconBox" :style="{ background: `${item.color}` }"
                                        @mouseenter="showPopover(index)" @mouseleave="hidePopover(index)">
                                        <el-icon v-if="!item.icon">
                                            <Plus />
                                        </el-icon>
                                        <span class="icon iconfont" :class="item.icon"
                                           :style="item.color?'color: #ffffff;font-size: 26px;':'font-size: 26px;color: #606266;'"></span>
                                    </div>
                                </template>
                                <!-- 选择区域 -->
                                <div class="popoverDialog">
                                    <el-form-item label="选择颜色" label-width="74px"
                                        style="margin-bottom: 10px;margin: 0 15px 18px 15px">
                                        <el-color-picker v-model="item.color" show-alpha :predefine="predefineColors" />
                                    </el-form-item>
                                    <el-form-item label="选择图标" label-width="74px"
                                        style="margin-bottom: 10px;margin: 0 15px 18px 15px">
                                        <div class="icon_ul">
                                            <div class="items" 
                                                :class="{ active: indexs === typeList[currentIndex].childItem[index].selectedIconIndex }"
                                                v-show="indexs > 10 && indexs < 118"
                                                v-for="(items, indexs) in url.glyphs" 
                                                :key="indexs"
                                                @click="selectIcon('icon-' + items.font_class, index, indexs)">
                                                <el-icon :size="20">
                                                    <SvgIcon :icon-class="'icon-' + items.font_class" :size="'20px'" ></SvgIcon>
                                                </el-icon>
                                            </div>
                                        </div>
                                    </el-form-item>
                                    <div class="popoverFooter">
                                        <!-- 添加清空按钮 -->
                                        <el-button type="default" class="white-bg-btn" plain @click="handleClearColor(index)">清空颜色</el-button>
                                        <el-button type="primary" class="white-bg-btn" plain @click="item.visible = false">关闭</el-button>
                                    </div>
                                </div>
                            </el-popover>
                            <div style="flex: 1;">
                                <el-form-item label="名称" label-width="40px" style="margin-bottom: 10px;">
                                    <el-input v-model="item.name" style="width:100%;" placeholder="请输入名称">
                                    </el-input>
                                </el-form-item>
                                <el-form-item label="链接" label-width="40px" style="margin-bottom: 0px;">
                                    <el-input v-model="item.link" style="width:100%;" placeholder="请输入链接">
                                    </el-input>
                                </el-form-item>
                            </div>
                        </div>
                        <div class="rightBox">
                            <el-image :src="icon_jian" @click="delItem(index)"
                                v-if="typeList[currentIndex].childItem.length != 1" width="32"></el-image>
                            <el-image :src="icon_jia" @click="addItem(index)" width="32"></el-image>
                        </div>
                    </div>
                </div>
            </el-form>
            <div class="fixed-btn-box2">
                <el-button type="primary" @click="submitForm(editFormRef)">保存更改</el-button>
                <el-button type="primary" class="white-bg-btn" plain @click="resetForm(editFormRef)">取消</el-button>
            </div>
        </div>
        <!-- 添加分类弹窗 -->
        <Model title="添加分类" :modelShow="dialogVisible" width="40" @cancel="resetForm2" @confirm="submitForm2">
            <el-form label-width="74px" size="default">
                <div class="FriendLink" v-for="(item, index) in newTypeList" :key="index">
                    <div class="leftBox">
                        <div style="flex: 1;display: flex;align-items: center;">
                            <el-form-item label="分类名称" style="margin-bottom: 10px;flex: 1;">
                                <el-input v-model="item.name" style="width:100%;" placeholder="请输入分类名称">
                                </el-input>
                            </el-form-item>
                            <el-form-item label="是否显示" prop="is_show" label-width="100px" style="margin-bottom: 12px;">
                                <el-switch v-model="item.is_show" :active-value="1" :inactive-value="0"
                                    active-color="#00BE65" inactive-color="#C5C5C5">
                                </el-switch>
                            </el-form-item>
                        </div>
                    </div>
                    <div class="rightBox2">
                        <el-image :src="icon_jian" @click="delItem2(index)" v-if="newTypeList.length != 1"
                            width="32"></el-image>
                        <el-image :src="icon_jia" @click="addItem2(index)" width="32"></el-image>
                    </div>
                </div>
            </el-form>
        </Model>
    </div>
</template>
<script lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { ref, h, onMounted, reactive, watch, nextTick } from 'vue'
import url from '../../../assets/fonts/iconfont.json'
import icon_jia from '../../../assets/images/icon_jia.png'
import icon_jian from '../../../assets/images/icon_jian.png'
import { editSitecfgCfg } from '../../Api/Setting'
interface PropsType {
    infoData?: any
    id?: string
}
const props = withDefaults(defineProps<PropsType>(), {
    infoData: [],
    id: '',
})
interface EmitType {
    (e: 'getConfig'): void
    (e: 'getConfigInfo', data: any): void
}
const emit = defineEmits<EmitType>()
const editForm = reactive<any>({
    type_id: '',
    module_name: '',
})
const typeList = ref<any>([
    {
        name: '',
        id: '',
        is_show: 1,
        childItem: [
            {
                icon: '',
                color: '',
                name: '',
                link: '',
                visible: false,
                selectedIconIndex: -1  // 新增：记录选中的图标索引
            }
        ]
    }
])
const editFormRef = ref<FormInstance>()
const editFormRules = reactive<FormRules>({
    type_id: [{ required: true, message: '请选择分类', trigger: 'blur' }],
    module_name: [{ required: true, message: '请输入模块名称', trigger: 'blur' }],
})
const dialogVisible = ref<boolean>(false)
const popover = ref<any>(null)
const showPopover = (index: number) => {
    typeList.value[currentIndex.value].childItem.forEach((item: any) => {
        item.visible = false
    })
    typeList.value[currentIndex.value].childItem[index].visible = true
}
const hidePopover = (index: number) => {
    typeList.value[currentIndex.value].childItem[index].visible = true
}
const predefineColors = ref([
    '#ff4500',
    '#ff8c00',
    '#ffd700',
    '#90ee90',
    '#00ced1',
    '#1e90ff',
    '#c71585',
    'rgba(255, 69, 0, 0.68)',
    'rgb(255, 120, 0)',
    'hsv(51, 100, 98)',
    'hsva(120, 40, 94, 0.5)',
    'hsl(181, 100%, 37%)',
    'hsla(209, 100%, 56%, 0.73)',
    '#c7158577',
])
// 通过id拿到他的子级
const currentIndex = ref<number>(0)
const changeType = async (id: number | string) => {
    typeList.value.forEach((item: any, index: number) => {
        if (Number(item.id) === Number(id)) {
            currentIndex.value = index
        }
    });
}
const addItem = (index: number) => {
    // 添加的时候判断桑一个是否填写了名字
    if (!typeList.value[currentIndex.value].childItem[index].name) {
        return ElMessage.error('请填写完整信息再提交!')
    }
    typeList.value[currentIndex.value].childItem.push({
        icon: '',
        color: '',
        name: '',
        link: '',
        visible: false
    })
}
const delItem = (index: number) => {
    typeList.value[currentIndex.value].childItem.splice(index, 1)
}
const resetDate = async () => {
    typeList.value.forEach((item: any) => {
        item.childItem.forEach((items: any) => {
            items.visible = false
        })
    })
}
// 首页配置数据提交
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid: any) => {
        if (valid) {
            await resetDate()
            const res: any = await editSitecfgCfg({ id: props.id, cfg_val: JSON.stringify({ module_name: editForm.module_name, typeList: typeList.value }) })
            if (res.code !== 1) return ElMessage.error(res.msg)
            ElMessage.success(res.msg)
            emit('getConfig')
            setTimeout(() => {
                if (props.infoData && Object.keys(props.infoData).length !== 0) {
                    typeList.value = JSON.parse(JSON.stringify(props.infoData)).typeList
                    editForm.module_name = JSON.parse(JSON.stringify(props.infoData)).module_name
                    editForm.type_id = typeList.value[currentIndex.value].id
                }
            }, 500);
        } else {
            console.log('error submit!')
        }
    })
}
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    emit('getConfig')
    setTimeout(() => {
        if (props.infoData && Object.keys(props.infoData).length !== 0) {
            typeList.value = JSON.parse(JSON.stringify(props.infoData)).typeList
            editForm.module_name = JSON.parse(JSON.stringify(props.infoData)).module_name
            editForm.type_id = typeList.value[currentIndex.value].id
        }
    }, 500);
    // formEl.resetFields()
}
// 添加分类祥光操作
const newTypeList = ref<any>([])
const Add = () => {
    newTypeList.value = JSON.parse(JSON.stringify(typeList.value))
    dialogVisible.value = true
}
const delItem2 = (index: number) => {
    // 判断是都有id
    if (!newTypeList.value[index].id) {
        newTypeList.value.splice(index, 1)
    } else {
        ElMessageBox({
            title: '温馨提示',
            message: h('p', { style: 'font-weight:bold;font-size: 15px;color: #333333;' }, [
                h('span', null, '确定要删除？'),
                h('p', { style: 'font-size: 14px;font-weight:normal;color: rgba(0,0,0,0.65);margin-top:10px;' }, '删除后将无法恢复，分类下的所有数据都会清除，确定要继续吗?'),
            ]),
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            beforeClose: async (action, instance, done) => {
                if (action === 'confirm') {
                    newTypeList.value.splice(index, 1)
                    done()
                } else {
                    done()
                }
            }
        }).then((action) => {
        })
    }
}
const addItem2 = (index: number) => {
    newTypeList.value.splice(index + 1, 0, {
        name: '',
        id: '',
        is_show: 1,
        childItem: [
            {
                icon: '',
                color: '',
                name: '',
                link: '',
                visible: false
            }
        ]
    })
}
// 生成八位随机数
const generateRandomId = () => {
    // 生成一个8位的随机数
    return Math.floor(10000000 + Math.random() * 90000000).toString();
}
// 监测某个字段是否存在重复情况
const hasDuplicateNames = () => {
    const names = newTypeList.value.map((item: any) => item.name);
    return (new Set(names)).size !== names.length
}
// 添加分类提交
const submitForm2 = async () => {
    let i = 0
    newTypeList.value.forEach((item: any) => {
        if (!item.name) {
            i++
        }
    })
    if (i > 0) {
        return ElMessage.error('请填写完整信息再提交!')
    }
    if (hasDuplicateNames()) {
        return ElMessage.error('分类名称存在重复情况!')
    }
    newTypeList.value.forEach((item: any) => {
        if (!item.id) {
            item.id = generateRandomId()
        }
    })
    typeList.value = [...newTypeList.value]
    dialogVisible.value = false
}
const resetForm2 = () => {
    dialogVisible.value = false
}
// 图标选择器
const icons = ref<any>([])
const selectIcon = async (val: string, childIndex: number, iconIndex: number) => {
    // 保存选中的图标类名
    typeList.value[currentIndex.value].childItem[childIndex].icon = val;
    // 保存当前选中的图标索引
    typeList.value[currentIndex.value].childItem[childIndex].selectedIconIndex = iconIndex;
};
// 添加清空颜色方法（index为当前操作的子项索引）
const handleClearColor = (index: number) => {
    // 清空当前分类下对应子项的颜色
    typeList.value[currentIndex.value].childItem[index].color = '';
};
watch(
    () => [typeList.value, editForm.module_name],
    (newVal: any, oldVal: any) => {
        emit('getConfigInfo', JSON.stringify({ typeList: typeList.value, module_name: editForm.module_name }))
    },
    { deep: true, immediate: true }
)
onMounted(() => {
    if (props.infoData && Object.keys(props.infoData).length !== 0) {
        typeList.value = JSON.parse(JSON.stringify(props.infoData)).typeList
        editForm.module_name = JSON.parse(JSON.stringify(props.infoData)).module_name
        editForm.type_id = typeList.value[0].id
    }
})
defineExpose({ typeList, submitForm, editFormRef, resetDate, editForm })

</script>
<style lang="scss" scoped>
.edtiArticle {
    height: 100%;

    .drawerTop {
        height: 100%;
        position: relative;

        .el-form {
            height: 100%;
        }
        .title {
            height: 48px;
            line-height: 48px;
            border-bottom: 1px solid #E4E4E4;
            font-weight: bold;
            font-size: 14px;
            color: #333333;
            padding: 0 20px;
        }

        .seetingBox {
            padding: 20px;
            height: calc(100% - 130px);
            overflow-y: scroll;
            box-sizing: border-box;

            .tips {
                display: flex;
                font-size: 12px;
                align-items: center;

                .el-image {
                    display: flex;
                    align-items: center;
                    margin-right: 5px;
                }
            }

        }
    }

    .fixed-btn-box2 {
        left: 0px;
        right: 0px;
        position: absolute;
        bottom: 0px;
        box-shadow: 0px -3px 4px 1px rgba(0, 0, 0, 0.06);

        .el-button {
            margin: 15px;
            margin-right: 15px;
            margin-left: 0px;
            float: right;
        }
    }

    .FriendLink {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
        padding: 0 0 0 15px;

        .leftBox {
            flex: 1;
            background: #F5F5F5;
            border-radius: 4px 4px 4px 4px;
            padding: 18px;
            display: flex;
            align-items: center;

            .iconBox {
                width: 48px;
                height: 48px;
                background: #FFFFFF;
                border-radius: 50%;
                border: 1px solid #E3E3E3;
                margin-right: 15px;
                display: flex;
                align-items: center;
                justify-content: center;
            }
        }

        .rightBox {
            width: 32px;
            margin-left: 15px;

            .el-image {
                margin: 2px 0;
                cursor: pointer;
            }
        }

        .rightBox2 {
            width: 100px;

            .el-image {
                margin-left: 15px;
                cursor: pointer;
            }
        }
    }
}

.icon_ul {
    height: 300px;
    overflow-y: scroll;

    .items {
        display: inline-block;
        width: 32px;
        height: 32px;
        border-radius: 16px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        border: 1px solid #E3E3E3;  // 默认边框颜色
        margin: 0 10px 10px 0;
        cursor: pointer;  // 添加手型光标
        box-sizing: border-box;

        // 选中状态样式
        &.active {
            border: 2px solid #51b5e2;  // 蓝色边框
        }
    }
}

.popoverFooter {
    border-top: 1px solid #E4E4E4;
    padding: 12px 12px 0 12px;
    text-align: right;
}
</style>
<style>
.el-popover {
    padding: 12px 0 !important;
}
.el-color-picker__panel .el-button.is-text{
   display:none;
}
</style>